package core;

import fileoperation.FileStatus;
import gitobject.Commit;
import repository.Repository;
import stage.Index;
import utils.setOperation;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.HashSet;

public class JitCheckout {

    public JitCheckout() throws IOException {
    }

    /**
     * switch to the given branch
     * @param branchName
     */
    public static void checkout(String branchName) throws IOException {
        if(!FileStatus.branchExist(branchName)){
            System.out.println("error: pathspec" + "'" + branchName + "'"+ "did not match any file(s) known to jit\n");
        }
        Path path = Paths.get(Repository.getGitDir() + File.separator + "refs"
                + File.separator + "heads" + File.separator + branchName);
        String commitid = Files.readString(path);
        syncronize(commitid);
        branch.Branch branch = new branch.Branch(branchName);
        branch.changeHead();
    }

    /**
     * create and switch to a new branch
     * @param branchName
     * @throws IOException
     */
    public static void createCheckout(String branchName) throws IOException {
        JitBranch.branch(branchName);
        checkout(branchName);
    }

    /**
     * syncronize working directory to target commit state
     * @param target
     * @throws IOException
     */
    public static void syncronize(String target) throws IOException {
        HashMap<String,String> nextFiles = null;
        HashMap<String,String> currFiles = null;
        Commit nextCommit = null;
        Commit currCommit = null;

        nextCommit = Commit.deserialize(target);
        String treePath = nextCommit.getTree(); 

        nextFiles = JitReset.getAllBlob(treePath);
        currCommit = Commit.deserialize(JitBranch.getCurBranch().commitID);
        String treePath1 = currCommit.getTree();

        currFiles = JitReset.getAllBlob(treePath1);

        //Hash:String
        HashSet<String> nextFilesKeySet  = setOperation.getDifference(nextFiles,currFiles);//add
        HashSet<String> currFilesKeySet = setOperation.getDifference(currFiles,nextFiles);//del

        //update working directory
        JitReset.WorkTreeModify(nextFilesKeySet,nextFiles,currFilesKeySet,currFiles);

        System.out.printf("HEAD is now at %s %s",target.substring(0,7), nextCommit.getMessage());
    }
}
